package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误！");
        }
        // 检查验证码
//        Object cacheCode = session.getAttribute("code");
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        log.info("cacheCode: " + cacheCode);
        if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
            // 不一致，报错
            return Result.fail("验证码错误");
        }
        // 一致，根据手机号查询用户
        User user = query().eq("phone", loginForm.getPhone()).one();
        // 不存在，创建用户并保存， NickName为随机10位字符
        if (user == null) {
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName("user_" + RandomUtil.randomString(10));
            save(user);
        }
        //保存用户到session
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        // 保存到redis中
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String token = UUID.randomUUID().toString(true);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);

        Map<String, String> stringUserMap = new HashMap<>();

        // 遍历 userMap，将所有值都转换为 String
        for (Map.Entry<String, Object> entry : userMap.entrySet()) {
            // 如果值不是 String 类型，将其转换为 String
            stringUserMap.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null);
        }

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, stringUserMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    // 批量免密登录，免验证码登录，传入一个phone的list,返回token的列表
    @Override
    public List<String> loginBatch(List<String> phones) {
        List<String> tokens = phones.stream().map(phone -> {
            User user = query().eq("phone", phone).one();
            UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
            String token = UUID.randomUUID().toString(true);
            Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);

            Map<String, String> stringUserMap = new HashMap<>();

            // 遍历 userMap，将所有值都转换为 String
            for (Map.Entry<String, Object> entry : userMap.entrySet()) {
                // 如果值不是 String 类型，将其转换为 String
                stringUserMap.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null);
            }

            stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, stringUserMap);
            stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
            return token;
        }).collect(Collectors.toList());
        // 将tokens保存为一个txt文件,每一行代表一个token
        return tokens;
    }
}
